using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.Drug;
using B.S.NewMedical.Api.Read.DTOS.Drug;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Drug
{
    /// <summary>
    /// 获取所有药品类型处理程序
    /// </summary>
    public class GetAllDrugCategoriesHandler : IRequestHandler<GetAllDrugCategoriesCommand, ApiResult<List<DrugCategoryDto>>>
    {
        private readonly IBaseRepository<DrugCategoryModel> _drugCategoryRepository;
        private readonly ILogger<GetAllDrugCategoriesHandler> _logger;
        private readonly IMapper _mapper;

        public GetAllDrugCategoriesHandler(
            IBaseRepository<DrugCategoryModel> drugCategoryRepository,
            ILogger<GetAllDrugCategoriesHandler> logger,
            IMapper mapper)
        {
            _drugCategoryRepository = drugCategoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<DrugCategoryDto>>> Handle(GetAllDrugCategoriesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取所有药品类型");

                // 查询所有未删除的药品类型
                var drugCategories = await _drugCategoryRepository.GetAll()
                    .Where(dc => !dc.IsDeleted)
                    .OrderBy(dc => dc.Id)
                    .ToListAsync(cancellationToken);

                // 转换为DTO
                var drugCategoryDtos = _mapper.Map<List<DrugCategoryDto>>(drugCategories);

                return new ApiResult<List<DrugCategoryDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取药品类型成功",
                    Data = drugCategoryDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取药品类型时发生异常");
                return new ApiResult<List<DrugCategoryDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取药品类型失败：" + ex.Message,
                    Data = new List<DrugCategoryDto>()
                };
            }
        }
    }
} 